package com.example.sunmiv1.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sunmiv1.R;
import com.example.sunmiv1.dialog.VipLoginDialog;
import com.example.sunmiv1.entity.GoodBean;
import com.example.sunmiv1.entity.LoginEntity;
import com.example.sunmiv1.entity.PrintInfoBean;
import com.example.sunmiv1.entity.ShopCouponInfo;
import com.example.sunmiv1.entity.VipListBean;
import com.example.sunmiv1.listener.TextChangeListener;
import com.example.sunmiv1.scan.InfraredScanActivity;
import com.example.sunmiv1.utils.ByteArrayTohexHepler;
import com.example.sunmiv1.utils.KotlinUtils;
import com.example.sunmiv1.utils.LogUtil;
import com.example.sunmiv1.utils.MathUtil;
import com.example.sunmiv1.utils.Tools;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.GsonUtils;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.LoadingDialog;
import com.example.sunmiv1.utils.net.TextCallBack;
import com.example.sunmiv1.utils.printUtil;
import com.example.sunmiv1.utils.zxing.Constant;
import com.example.sunmiv1.utils.zxing.activity.CaptureActivity;
import com.example.sunmiv1.vm.ChoosePaymentViewModel;

import org.json.JSONException;
import org.json.JSONObject;
import org.pay.PayCallback;
import org.pay.gate.model.PayGateReqModel;
import org.pay.gate.model.PayGateRespModel;
import org.pay.PayUtils;
import org.xprinter.XprinterManager;

import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.example.sunmiv1.utils.ByteArrayTohexHepler.ByteArrayToHexString;
import static com.example.sunmiv1.utils.ByteArrayTohexHepler.flipHexStr;

import net.nyx.printerservice.print.DeviceServiceChannel;
import net.nyx.printerservice.print.MemoryCacheManager;

@RequiresApi(api = Build.VERSION_CODES.N)
public class ChoosePaymentActivity extends FragmentActivity {

    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_title)
    TextView titleTitle;
    @BindView(R.id.choosePayment_aliPay)
    LinearLayout choosePaymentAliPay;
    @BindView(R.id.choosePayment_wxPay)
    LinearLayout choosePaymentWxPay;
    @BindView(R.id.choosePayment_vipPay)
    LinearLayout choosePaymentVipPay;
    @BindView(R.id.choosePayment_vipLogin_edit)
    EditText choosePaymentVipLoginEdit;
    @BindView(R.id.choosePayment_vipLogin_sure)
    TextView choosePaymentVipLoginSure;
    @BindView(R.id.choosePayment_vipLogin_linear)
    LinearLayout choosePaymentVipLoginLinear;
    @BindView(R.id.choosePayment_onlinePay_name)
    TextView choosePaymentOnlinePayName;
    @BindView(R.id.choosePayment_onlinePay_edit)
    EditText choosePaymentOnlinePayEdit;
    @BindView(R.id.choosePayment_onlinePay_scavenging)
    ImageView choosePaymentOnlinePayScavenging;
    @BindView(R.id.choosePayment_onlinePay_sure)
    TextView choosePaymentOnlinePaySure;
    @BindView(R.id.choosePayment_onlinePay_linear)
    LinearLayout choosePaymentOnlinePayLinear;
    @BindView(R.id.choosePayment_vipLogin_close)
    ImageView choosePaymentVipLoginClose;
    @BindView(R.id.choosePayment_onlinePay_close)
    ImageView choosePaymentOnlinePayClose;
    @BindView(R.id.choosePayment_money)
    LinearLayout choosePaymentMoney;
    @BindView(R.id.choosePayment_payable)
    TextView choosePaymentPayable;
    @BindView(R.id.choosePayment_otherPay)
    LinearLayout choosePaymentOtherPay;
    @BindView(R.id.choosePayment_otherPay_close)
    ImageView choosePaymentOtherPayClose;
    @BindView(R.id.choosePayment_otherPay_name)
    TextView choosePaymentOtherPayName;
    @BindView(R.id.choosePayment_otherPay_payable)
    TextView choosePaymentOtherPayPayable;
    @BindView(R.id.choosePayment_otherPay_sure)
    TextView choosePaymentOtherPaySure;
    @BindView(R.id.choosePayment_otherPay_linear)
    LinearLayout choosePaymentOtherPayLinear;
    @BindView(R.id.choosePayment_vipLogin_scavenging)
    ImageView choosePaymentVipLoginScavenging;

    @BindView(R.id.choosePayment_cardNum)
    TextView choosePaymentCardNum;
    @BindView(R.id.choosePayment_name)
    TextView choosePaymentName;
    @BindView(R.id.choosePayment_grade)
    TextView choosePaymentGrade;
    @BindView(R.id.choosePayment_integral)
    TextView choosePaymentIntegral;
    @BindView(R.id.choosePayment_balance)
    TextView choosePaymentBalance;
    @BindView(R.id.choosePayment_allPrice)
    TextView choosePaymentAllPrice;
    @BindView(R.id.choosePayment_discount)
    TextView choosePaymentDiscount;
    @BindView(R.id.choosePayment_discountMoney)
    TextView choosePaymentDiscountMoney;
    @BindView(R.id.choosePayment_realPay)
    EditText choosePaymentRealPay;
    @BindView(R.id.sv_choosePayment_vipInfo)
    LinearLayout svChoosePaymentVipInfo;
    @BindView(R.id.tv_choosePayment_loginOut)
    TextView tvChoosePaymentLoginOut;
    @BindView(R.id.choosePayment_integralMoney)
    TextView choosePaymentIntegralMoney;
    @BindView(R.id.vipPass_close)
    ImageView vipPassClose;
    @BindView(R.id.vipPass_pass)
    EditText vipPassPass;
    @BindView(R.id.vipPass_sure)
    TextView vipPassSure;
    @BindView(R.id.vipPass_linear)
    LinearLayout vipPassLinear;
    @BindView(R.id.switch_flag)
    Switch switchFlag;
    @BindView(R.id.ll_integral)
    LinearLayout llIntegral;
    @BindView(R.id.ll_integralMoney)
    LinearLayout llIntegralMoney;
    @BindView(R.id.tv_insufficient_title)
    TextView tvInsufficientTitle;
    @BindView(R.id.tv_insufficient)
    TextView tvInsufficient;
    @BindView(R.id.tv_insufficient_cancel)
    TextView tvInsufficientCancel;
    @BindView(R.id.tv_insufficient_confirm)
    TextView tvInsufficientConfirm;
    @BindView(R.id.ll_insufficient)
    LinearLayout llInsufficient;
    @BindView(R.id.choosePayment_otherPay_payList)
    Spinner choosePaymentOtherPayPayList;
    @BindView(R.id.choosePayment_smallChange)
    TextView choosePaymentSmallChange;
    @BindView(R.id.lin_choosePayment_money)
    LinearLayout linChoosePaymentMoney;
    @BindView(R.id.lin_choosePayment_discount)
    LinearLayout linChoosePaymentDiscount;
    @BindView(R.id.tv_choosePayment_coupon)
    TextView tvChoosePaymentCoupon;
    @BindView(R.id.lin_choosePayment_coupon)
    LinearLayout linChoosePaymentCoupon;
    @BindView(R.id.tv_choosePayment_ShopCoupon)
    TextView tvChoosePaymentShopCoupon;
    @BindView(R.id.iv_choosePayment_ShopCoupon)
    ImageView ivChoosePaymentShopCoupon;
    @BindView(R.id.lin_choosePayment_shopCoupon)
    LinearLayout linChoosePaymentShopCoupon;
    @BindView(R.id.choosePayment_creditMoney)
    TextView choosePaymentCreditMoney;
    @BindView(R.id.choosePayment_credit)
    LinearLayout choosePaymentCredit;
    @BindView(R.id.pay_order_amount)
    TextView mPayOrderAmount;

    private Context context;
    private ACache aCache;
    private LoadingDialog loadingDialog;

    //    private VipListBean vipinfoBean;
    private VipListBean.InfoBean infoBean;
    private List<GoodBean.DataBean.GoodsBean> list;
    private double allPrice = 0;//商品總金額
    private double realPay = 0;//實際支付的金額
    private double mMoney=0;

    private double integralDiscount = 0;//會員積分抵現
    private double discountMoney = 0;//會員優惠金額
    private int allIntegral = 0;
    private int integralPayFlag = 1;//1爲默認 2,金錢抵用低分 3,使用商品原價支付
    private int isVip;
    //是否開啓積分抵扣
    private boolean integralFlag = false;

    //需要使用的積分
    private int needIntegral = 0;
    //積分不足需要的金額
    private double needIntegralMoney = 0;
    private int PayFlag = 0;//支付方式：1,現金支付；3，微信支付 4,支付寶支付 5，會員支付 7,其他支付
    private Intent intent;
    private DecimalFormat decimalFormat = new DecimalFormat("0.00");//構造方法的字符格式這裏如果小數不足2位,會以0補足.

    //nfc
    private NfcAdapter mNfcAdapter;
    private PendingIntent pi;
    private boolean isSupportNfc, isOpenNfc;
    private static final String TAG = "ChoosePaymentActivity";

    private int otherPayIndex = 9999;
    private LoginEntity loginEntity;
    private List<LoginEntity.DataBean.OtherPayListBean> otherPayList = new ArrayList<>();
    private List<VipListBean.InfoBean.CouponListBean> couponList = new ArrayList<>();
    private int couponIndex = 9999;
    private double couponMoney = 0;
    private String mOrderNo="";

    private ChoosePaymentViewModel mViewModel;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    isVip = 1;
                    choosePaymentVipLoginLinear.setVisibility(View.GONE);
                    svChoosePaymentVipInfo.setVisibility(View.VISIBLE);
                    linChoosePaymentDiscount.setVisibility(View.VISIBLE);
                    linChoosePaymentCoupon.setVisibility(View.VISIBLE);
                    linChoosePaymentShopCoupon.setVisibility(View.GONE);
                    tvChoosePaymentShopCoupon.setText("");
                    couponMoney = 0;
                    choosePaymentVipLoginEdit.setText("");
//                    infoBean = vipinfoBean.getInfo().get(0);
                    choosePaymentCardNum.setText(infoBean.getCardnum());
                    choosePaymentName.setText(infoBean.getName());
                    choosePaymentGrade.setText(infoBean.getGrade_name());
                    choosePaymentIntegral.setText(infoBean.getIntegral());
                    choosePaymentBalance.setText(infoBean.getBalance());
                    choosePaymentDiscount.setText(infoBean.getDiscount() + "");
                    choosePaymentCreditMoney.setText(getString(R.string.choosePaymentQuota) + infoBean.getCreditQuota());
                    couponList.addAll(infoBean.getCouponList());
                    countMoney();
                    break;
                case 2:
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_choose_payment);
        context = this;
        mViewModel=new ChoosePaymentViewModel(this);
        mViewModel.init();
        aCache = ACache.get(context);
        loadingDialog = new LoadingDialog(context);
        ButterKnife.bind(this);
        titleTitle.setText(R.string.choosePaymentType);
        list = new ArrayList<>();
        loginEntity = GsonUtils.JsonToBean(aCache.getAsString("loginInfo"), LoginEntity.class);
        list.addAll((List<GoodBean.DataBean.GoodsBean>) getIntent().getSerializableExtra("list"));
        isVip = getIntent().getIntExtra("isVip", 0);
        if ("0".equals(aCache.getAsString("credit"))) {
            choosePaymentCredit.setVisibility(View.INVISIBLE);
        } else {
            choosePaymentCredit.setVisibility(View.VISIBLE);
        }
        if (isVip == 1) {
            infoBean = (VipListBean.InfoBean) getIntent().getSerializableExtra("vipInfo");
            Message msg = new Message();
            msg.what = 1;
            handler.sendMessage(msg);
        } else {
            LogUtil.e("無碼商品的信息：\n無碼商品的信息：\n" + Arrays.deepToString(list.toArray()));
            choosePaymentCreditMoney.setText(getString(R.string.choosePaymentQuota));
            countMoney();
        }
        mOrderNo=getIntent().getStringExtra("order_no");
//        choosePaymentAllPrice.setText(getIntent().getDoubleExtra("allPrice", 0) + "");
        printUtil.getInstance().connectPrinterService(context);

        //nfc
        PackageManager packageManager = this.getPackageManager();
        isSupportNfc = packageManager.hasSystemFeature(PackageManager.FEATURE_NFC);
        Log.e(TAG, "onCreate: isSupportNfc=" + isSupportNfc);
        if (isSupportNfc) {
            mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
            pi = PendingIntent.getActivity(this, 0, new Intent(this, getClass())
                    .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
            if (mNfcAdapter != null && !mNfcAdapter.isEnabled()) {
                isOpenNfc = false;
            } else {
                isOpenNfc = true;
            }
        }
        initListener();
    }

    private void initListener() {
        switchFlag.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                if ("1".equals(aCache.getAsString("integral_arrive_cash"))) {
                    integralFlag = true;
                } else {
                    integralFlag = false;
                }
            } else {
                integralFlag = false;
            }
            countMoney();
        });
    }

    private void setOtherPayListAdapter() {
        ArrayAdapter<LoginEntity.DataBean.OtherPayListBean> adapter = new ArrayAdapter<LoginEntity.DataBean.OtherPayListBean>(context, android.R.layout.simple_list_item_1, otherPayList) {
            @Override
            public View getDropDownView(int pos, @Nullable View convertView, @NonNull ViewGroup parent) {
                @SuppressLint("ViewHolder") View view = ((Activity) context).getLayoutInflater().inflate(android.R.layout.simple_list_item_single_choice, parent, false);
                final TextView text = view.findViewById(android.R.id.text1);
                text.setText(otherPayList.get(pos).getName());
                text.setTextSize(14);
                return view;
            }

            @NonNull
            @Override
            public View getView(int pos, @Nullable View convertView, @NonNull ViewGroup parent) {
                @SuppressLint("ViewHolder") View view = ((Activity) context).getLayoutInflater().inflate(android.R.layout.simple_list_item_1, parent, false);
                final TextView text = view.findViewById(android.R.id.text1);
                text.setText(otherPayList.get(pos).getName());
                text.setTextSize(14);
                return view;
            }
        };
        choosePaymentOtherPayPayList.setAdapter(adapter);
        choosePaymentOtherPayPayList.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                otherPayIndex = pos;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    /**
     * 用來計算商品的折扣和總價格
     */
    private void countMoney() {
        allPrice = 0;//商品總金額
        integralDiscount = 0;//會員積分抵扣
        allIntegral = 0;
        discountMoney = 0;
        for (int i = 0; i < list.size(); i++) {
            String originalPrice = "";
            double price = 0;
            int integral = 0;
            GoodBean.DataBean.GoodsBean goods = list.get(i);
            double vip_discount = 1;
            if (((isVip == 1 && "1".equals(goods.getVip_retail_state()) && (!"1".equals(goods.getPlus_mem_status()) || !"2".equals(infoBean.getPlus_type()))) || (isVip == 1 && "1".equals(goods.getVip_retail_state()) && !"".equals(goods.getCheng_price()))) && infoBean != null) {
                vip_discount = infoBean.getDiscount();
            }
            if (1 == goods.getIs_gift_good()) {
                continue;
            }
            if ("".equals(goods.getCheng_price())) {
                if (isVip == 1) {
                    if ("2".equals(infoBean.getPlus_type()) && "1".equals(goods.getPlus_mem_status())) { //plus會員
                        if (isSkuGood(i, list)) { //判斷規格商品
                            if (integralPayFlag != 3 && !TextUtils.isEmpty(goods.getSkujson().get(0).getPlus_price())
                                    || integralPayFlag == 3 && (TextUtils.isEmpty(goods.getSkujson().get(0).getPlus_mem_integral()) ||
                                    Integer.parseInt(goods.getSkujson().get(0).getPlus_mem_integral()) == 0)) {
                                price = getVipPrice(isVip, goods, goods.getSkujson().get(0).getPlus_price());
                                originalPrice = goods.getSkujson().get(0).getPlus_price();
                                if (integralPayFlag == 1 && !TextUtils.isEmpty(goods.getSkujson().get(0).getPlus_mem_integral())) {
                                    integral += Integer.parseInt(goods.getSkujson().get(0).getPlus_mem_integral());
                                }
                            } else {
                                price = getVipPrice(isVip, goods, goods.getSkujson().get(0).getRetail_price());
                                originalPrice = goods.getSkujson().get(0).getRetail_price();
                            }
                        } else {
                            if (integralPayFlag != 3 && !TextUtils.isEmpty(goods.getPlus_price())
                                    || integralPayFlag == 3 && (TextUtils.isEmpty(goods.getPlus_mem_integral()) ||
                                    Integer.parseInt(goods.getPlus_mem_integral()) == 0)) {
                                price = getVipPrice(isVip, goods, goods.getPlus_price());
                                originalPrice = goods.getPlus_price();
                                if (integralPayFlag == 1 && !TextUtils.isEmpty(goods.getPlus_mem_integral())) {
                                    integral += Integer.parseInt(goods.getPlus_mem_integral());
                                }

                            } else {
                                price = getVipPrice(isVip, goods, goods.getRetail_price());
                                originalPrice = goods.getRetail_price();
                            }
                        }
                    } else { //常規會員
                        if ("1".equals(goods.getVip_retail_state())) {
                            if (isSkuGood(i, list)) {
                                if ("2".equals(goods.getSkujson().get(0).getStore_mem_status())) {
                                    price = getVipPrice(isVip, goods, goods.getRetail_price());
                                    originalPrice = goods.getRetail_price();
                                } else {
                                    if (integralPayFlag != 3 && !TextUtils.isEmpty(goods.getSkujson().get(0).getStore_mem_price())
                                            || integralPayFlag == 3 && (TextUtils.isEmpty(goods.getSkujson().get(0).getStore_mem_integral()) ||
                                            Integer.parseInt(goods.getSkujson().get(0).getStore_mem_integral()) == 0)) {
                                        price = getVipPrice(isVip, goods, goods.getSkujson().get(0).getStore_mem_price());
                                        originalPrice = goods.getSkujson().get(0).getStore_mem_price();
                                        if (integralPayFlag == 1 && !TextUtils.isEmpty(goods.getSkujson().get(0).getStore_mem_integral())) {
                                            integral += Integer.parseInt(goods.getSkujson().get(0).getStore_mem_integral());
                                        }
                                    } else {
                                        price = getVipPrice(isVip, goods, goods.getRetail_price());
                                        originalPrice = goods.getRetail_price();
                                    }
                                }
                            } else {
                                if ("2".equals(goods.getStore_mem_status())) {
                                    price = getVipPrice(isVip, goods, goods.getRetail_price());
                                    originalPrice = goods.getRetail_price();
                                } else {
                                    if (integralPayFlag != 3 && !TextUtils.isEmpty(goods.getStore_mem_price())
                                            || integralPayFlag == 3 && (TextUtils.isEmpty(goods.getStore_mem_integral()) ||
                                            Integer.parseInt(goods.getStore_mem_integral()) == 0)) {
                                        price = getVipPrice(isVip, goods, goods.getStore_mem_price());
                                        originalPrice = goods.getStore_mem_price();
                                        if (integralPayFlag == 1 && !TextUtils.isEmpty(goods.getStore_mem_integral())) {
                                            Log.e("===========3805", "countMoney: integral=" + goods.getStore_mem_integral());
                                            integral += Integer.parseInt(goods.getStore_mem_integral());
                                        }
                                    } else {
                                        price = getVipPrice(isVip, goods, goods.getRetail_price());
                                        originalPrice = goods.getRetail_price();
                                    }
                                }
                            }
                        } else {
                            if (isSkuGood(i, list)) {
                                if ("2".equals(goods.getSkujson().get(0).getStore_mem_status())) {
                                    price = getVipPrice(isVip, goods, goods.getRetail_price());
                                    originalPrice = goods.getRetail_price();
                                } else {
                                    if (integralPayFlag != 3 && !TextUtils.isEmpty(goods.getSkujson().get(0).getStore_mem_price())
                                            || integralPayFlag == 3 && (TextUtils.isEmpty(goods.getSkujson().get(0).getStore_mem_integral()) ||
                                            Integer.parseInt(goods.getSkujson().get(0).getStore_mem_integral()) == 0)) {
                                        price = getVipPrice(isVip, goods, goods.getSkujson().get(0).getStore_mem_price());
                                        originalPrice = goods.getSkujson().get(0).getStore_mem_price();
                                        if (integralPayFlag == 1 && !TextUtils.isEmpty(goods.getSkujson().get(0).getStore_mem_integral())) {
                                            integral += Integer.parseInt(goods.getSkujson().get(0).getStore_mem_integral());
                                        }
                                    } else {
                                        price = getVipPrice(isVip, goods, goods.getRetail_price());
                                        originalPrice = goods.getRetail_price();
                                    }
                                }
                            } else {
                                if ("2".equals(goods.getStore_mem_status())) {
                                    price = getVipPrice(isVip, goods, goods.getRetail_price());
                                    originalPrice = goods.getRetail_price();
                                } else {
                                    if (integralPayFlag != 3 && !TextUtils.isEmpty(goods.getStore_mem_price())
                                            || integralPayFlag == 3 && (TextUtils.isEmpty(goods.getStore_mem_integral()) ||
                                            Integer.parseInt(goods.getStore_mem_integral()) == 0)) {
                                        price = Double.parseDouble(goods.getStore_mem_price());
                                        if (integralPayFlag == 1 && !TextUtils.isEmpty(goods.getStore_mem_integral())) {
                                            integral += Integer.parseInt(goods.getStore_mem_integral());
                                        }
                                    } else {
                                        price = Double.parseDouble(goods.getRetail_price());
                                    }
                                    originalPrice = price + "";
                                    price = getVipPrice(isVip, goods, price + "");
                                }
                            }
                        }
                    }
                } else {
                    if (isSkuGood(i, list)) {
                        if (goods.getSkujson().get(0).getRetail_price() != null &&
                                !TextUtils.isEmpty(goods.getSkujson().get(0).getRetail_price())) {
                            price = getVipPrice(0, goods, goods.getSkujson().get(0).getRetail_price());
                            originalPrice = goods.getSkujson().get(0).getRetail_price();
                        } else {
                            price = getVipPrice(0, goods, goods.getRetail_price());
                            originalPrice = goods.getRetail_price();
                        }
                    } else {
                        price = getVipPrice(0, goods, goods.getRetail_price());
                        originalPrice = goods.getRetail_price();
                    }
                }
                Log.e(TAG, "countMoney: 積分=" + integral);
                allPrice += MathUtil.mul(price, goods.getAgoods_count());
                discountMoney += MathUtil.sub(doubleAndMul(originalPrice, goods.getAgoods_count() + ""), doubleAndMul(price + "", goods.getAgoods_count() + ""));
                allIntegral += MathUtil.mul(integral, goods.getAgoods_count());
            } else {
                if (isVip == 1) {
                    price = MathUtil.mul(Double.parseDouble(goods.getCheng_price()), vip_discount);
                } else {
                    price = Double.parseDouble(goods.getCheng_price());
                }
                allPrice += price;
                discountMoney += MathUtil.sub(Double.parseDouble(goods.getCheng_price()), price);
                if ("1".equals(aCache.getAsString("manual_discount"))) {
                    double dis = goods.getSku_discount();
                    double p1 = Double.parseDouble(goods.getCheng_price());
                    double p2 = price;
                }
            }
        }
        discountMoney = MathUtil.round(discountMoney, 2);
        choosePaymentAllPrice.setText(MathUtil.add(allPrice, discountMoney) + "");
        mPayOrderAmount.setText("$ "+MathUtil.add(allPrice, discountMoney) + "");
        //積分優惠 基於訂單
        if ("1".equals(aCache.getAsString("marketing_methods"))) {
            if (infoBean != null) {
                if ("1".equals(aCache.getAsString("integral_arrive_cash"))) {
                    llIntegral.setVisibility(View.VISIBLE);
                    llIntegralMoney.setVisibility(View.VISIBLE);
                } else {
                    llIntegral.setVisibility(View.GONE);
                    llIntegralMoney.setVisibility(View.GONE);
                }
                if (integralFlag) {
                    double integralMoney = 0.00, needIntegral1 = 0.00;
                    if ("1".equals(aCache.getAsString("integral_arrive_cash"))) {
                        integralMoney = MathUtil.mul(allPrice, Double.parseDouble(aCache.getAsString("integral_arrive_cash_rate")));
                        double i = doubleAndMul(aCache.getAsString("integral_arrive_cash_data"), aCache.getAsString("integral_arrive_cash_price"));
                        double y = MathUtil.div(integralMoney, Double.parseDouble(aCache.getAsString("integral_arrive_cash_price")));
                        needIntegral1 = MathUtil.mul(i, y);
                        if (Double.parseDouble(infoBean.getIntegral()) > needIntegral1) {
                            allPrice = allPrice - integralMoney;
                            integralDiscount = integralMoney;
                            needIntegral = (int) needIntegral1;
                        } else {
                            double s = MathUtil.div(Double.parseDouble(infoBean.getIntegral()), i);
                            double discountMoney = MathUtil.mul(s, Double.parseDouble(aCache.getAsString("integral_arrive_cash_price")));
                            allPrice = allPrice - discountMoney;
                            integralDiscount = discountMoney;
                            needIntegral = (int) MathUtil.div(discountMoney, Double.parseDouble(aCache.getAsString("integral_arrive_cash_price")));
                        }
                        needIntegralMoney = integralDiscount;
                    }
                } else {
                    integralDiscount = 0;
                }
            }
        } else {//基於商品
            allPrice += needIntegralMoney;
        }

        allPrice = MathUtil.round(allPrice, 2);
        if (list.size() > 0 && allPrice <= 0) {
            allPrice = 0.01;
        }
        allPrice = Double.parseDouble(decimalFormat.format(allPrice));

        choosePaymentDiscountMoney.setText(discountMoney + "");
        choosePaymentIntegralMoney.setText(integralDiscount + "");
        setMoney();
    }
    private void setMoney() {
        realPay = allPrice;
        if (couponIndex != 9999) {
            realPay = MathUtil.sub(allPrice, Double.parseDouble(couponList.get(couponIndex).getReduce_money()));
        } else if (couponMoney != 0) {
            realPay = MathUtil.sub(allPrice, couponMoney);
        }
        boolean isUpdate=mViewModel.getMoney()!=realPay;
        mViewModel.setMoney(realPay);

        if(isUpdate){
            choosePaymentRealPay.setText(realPay + "");
        }
        realPay=mViewModel.getMoneyEditValue();
        choosePaymentPayable.setText("$" + realPay);
        //现金支付和其他支付里面的实付金额
        choosePaymentOtherPayPayable.setText(realPay+"");
    }

    private boolean isSkuGood(int i, List<GoodBean.DataBean.GoodsBean> chooseList) {
        return "2".equals(chooseList.get(i).getAttribute_state()) &&
                chooseList.get(i).getSkujson() != null &&
                chooseList.get(i).getSkujson().size() > 0;
    }


    /**
     * 獲取會員價格
     */
    private double getVipPrice(int type, GoodBean.DataBean.GoodsBean position, String retail_price) {//type 0:普通用戶 1:會員
        double price = 0;
        //開啓門店折上折
        if ("1".equals(aCache.getAsString("store_manual_discount"))) {
            if (type == 1 && "1".equals(position.getVip_retail_state()) && ("2".equals(position.getPlus_mem_status()) ||
                    "1".equals(position.getPlus_mem_status()) && !"2".equals(infoBean.getPlus_type()))) {
                price = MathUtil.mul(Double.parseDouble(retail_price), infoBean.getDiscount());
            } else {
                price = Double.parseDouble(retail_price);
            }
            price = doubleAndMul(price + "", position.getSku_discount() + "");
        } else {
            if (position.getSku_discount() == 1) {
                if (type == 1 && "1".equals(position.getVip_retail_state()) && ("2".equals(position.getPlus_mem_status()) ||
                        "1".equals(position.getPlus_mem_status()) && !"2".equals(infoBean.getPlus_type()))) {
                    price = MathUtil.mul(Double.parseDouble(retail_price), infoBean.getDiscount());
                } else {
                    price = doubleAndMul(retail_price, position.getSku_discount() + "");
                }
            } else {
                price = doubleAndMul(retail_price, position.getSku_discount() + "");
            }
        }
        if (price < 0.01) {
            price = 0.01;
        }
        return price;
    }


    /**
     * 獲取兩數相乘的數
     */
    private double doubleAndMul(String retail_price, String vipDiscount) {
        return MathUtil.round(MathUtil.mul(Double.parseDouble(retail_price),
                Double.parseDouble(vipDiscount)), 2);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mNfcAdapter != null && isSupportNfc && isOpenNfc) {
            mNfcAdapter.enableForegroundDispatch(this, pi, null, null);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        String ex_id;
        Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        String num1 = ByteArrayToHexString(tagFromIntent.getId());
        String num2 = flipHexStr(num1);
        Log.e(TAG, "onNewIntent: 1=" + num2);
        String num = "";
        if (num2.length() > 10) {
            try {
                num = ByteArrayTohexHepler.hex2String(num2);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            Long cardNo = Long.parseLong(num2, 16);
            Log.e(TAG, "onNewIntent: 2=" + cardNo);
            num = cardNo.toString();
        }
        if (num.length() != 10) {
            while (num.length() < 10) {
                num = "0" + num;
            }
        }
        ex_id = num;
        Log.e("==================", ex_id);
        //Toast.makeText(getApplicationContext(), num, Toast.LENGTH_SHORT).show();
        choosePaymentVipLoginEdit.setText(ex_id);
        choosePaymentVipLoginEdit.setSelection(ex_id.length());
    }

    private boolean judgeIntegral() {
        if (isVip == 1 && infoBean != null && allIntegral > 0 && Double.parseDouble(infoBean.getIntegral()) < allIntegral) {
            int vipIntegral = 0;
            vipIntegral = Integer.parseInt(infoBean.getIntegral());
            int subIntegral = (int) MathUtil.sub(allIntegral, vipIntegral);
            double need = MathUtil.div(subIntegral, Double.parseDouble(aCache.getAsString("integral_arrive_cash_data")));
            double needMoney = MathUtil.mul(need, Double.parseDouble(aCache.getAsString("integral_arrive_cash_price")));
            tvInsufficient.setText(getString(R.string.integralTip1) + subIntegral + getString(R.string.integralTip2) + needMoney + getString(R.string.integralTip3)
                    + aCache.getAsString("integral_arrive_cash_price") + getString(R.string.integralTip4) +
                    aCache.getAsString("integral_arrive_cash_data") + getString(R.string.integralTip5));
            llInsufficient.setVisibility(View.VISIBLE);
            return false;
        } else {
            return true;
        }
    }

    @OnClick({R.id.title_back, R.id.choosePayment_aliPay, R.id.choosePayment_wxPay, R.id.choosePayment_vipPay,
            R.id.choosePayment_vipLogin_sure, R.id.choosePayment_vipLogin_close, R.id.choosePayment_vipLogin_linear, R.id.choosePayment_onlinePay_scavenging,
            R.id.choosePayment_onlinePay_sure, R.id.choosePayment_onlinePay_close, R.id.choosePayment_onlinePay_linear, R.id.choosePayment_money,
            R.id.choosePayment_otherPay, R.id.choosePayment_otherPay_close, R.id.choosePayment_otherPay_sure,
            R.id.choosePayment_otherPay_linear, R.id.choosePayment_vipLogin_scavenging,
            R.id.tv_choosePayment_loginOut,
            R.id.vipPass_linear, R.id.vipPass_sure, R.id.vipPass_close,
            R.id.tv_insufficient_cancel, R.id.tv_insufficient_confirm, R.id.ll_insufficient,
            R.id.tv_choosePayment_coupon, R.id.iv_choosePayment_ShopCoupon,
            R.id.choosePayment_credit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.choosePayment_credit:
                if (isVip == 0) {
                    VipLoginDialog.newInstance()
                            .callback(o -> {
                                infoBean = (VipListBean.InfoBean) o;
                                Message msg = new Message();
                                msg.what = 1;
                                handler.sendMessage(msg);
                            })
                            .startShow(getSupportFragmentManager(), "")
                            .setCancelable(false);
                } else {
                    if (infoBean.getIsCreditUser() == 2) {
                        Toast.makeText(context, "不是賒賬用戶，無法賒賬", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    PayFlag = 8;
                    if (Double.parseDouble(infoBean.getCreditQuota()) >= realPay) {
                        Pay();
                    } else {
                        Toast.makeText(context, "會員賒賬額度不足", Toast.LENGTH_SHORT).show();
                    }
                }
                break;
            case R.id.iv_choosePayment_ShopCoupon:

                startQrCode();
                break;
            case R.id.tv_choosePayment_coupon:
                intent = new Intent(context, ChooseCouponActivity.class);
                intent.putExtra("allMoney", allPrice);
                intent.putExtra("couponList", (Serializable) couponList);
                intent.putExtra("couponIndex", couponIndex);
                intent.putExtra("chooseList", (Serializable) list);
                intent.putExtra("infoBean", infoBean);
                startActivityForResult(intent, 100);
                break;
            case R.id.tv_insufficient_cancel:
                llInsufficient.setVisibility(View.GONE);
                integralPayFlag = 3;
                countMoney();
                break;
            case R.id.tv_insufficient_confirm:
                llInsufficient.setVisibility(View.GONE);
                integralPayFlag = 2;
                double vipIntegral = Double.parseDouble(infoBean.getIntegral());
                double subIntegral = MathUtil.sub(allIntegral, vipIntegral);
                double need = MathUtil.div(subIntegral, Double.parseDouble(aCache.getAsString("integral_arrive_cash_data")));
                double needMoney = MathUtil.mul(need, Double.parseDouble(aCache.getAsString("integral_arrive_cash_price")));
                needIntegral = (int) (allIntegral - subIntegral);
                needIntegralMoney = needMoney;
                countMoney();
                break;
            case R.id.ll_insufficient:
                break;

            case R.id.vipPass_linear:
                break;
            case R.id.vipPass_sure:
                if (TextUtils.isEmpty(vipPassPass.getText().toString().trim())) {
                    Toast.makeText(context, "請輸入會員支付密碼", Toast.LENGTH_SHORT).show();
                    return;
                }
                Pay();
                break;
            case R.id.vipPass_close:
                vipPassPass.setText("");
                vipPassLinear.setVisibility(View.GONE);
                break;
            case R.id.tv_choosePayment_loginOut:
                Toast.makeText(context, "退出成功", Toast.LENGTH_SHORT).show();
                svChoosePaymentVipInfo.setVisibility(View.GONE);
                linChoosePaymentDiscount.setVisibility(View.GONE);
                couponIndex = 9999;
                couponList.clear();
                tvChoosePaymentCoupon.setText(R.string.pleaseChooseCoupon);
                linChoosePaymentCoupon.setVisibility(View.GONE);
                linChoosePaymentShopCoupon.setVisibility(View.VISIBLE);
                isVip = 0;
                infoBean = null;
                countMoney();
                break;
            case R.id.title_back:
                finish();
                break;
            case R.id.choosePayment_aliPay:
                if ("2".equals(aCache.getAsString("marketing_methods"))) {
                    boolean f = true;
                    if (integralPayFlag == 1) {
                        f = judgeIntegral();
                    }
                    if (!f) {
                        return;
                    }
                }
                startQrCode();
                PayFlag = 4;
                break;
            case R.id.choosePayment_wxPay:
                if ("2".equals(aCache.getAsString("marketing_methods"))) {
                    boolean f = true;
                    if (integralPayFlag == 1) {
                        f = judgeIntegral();
                    }
                    if (!f) {
                        return;
                    }
                }
                startQrCode();
                PayFlag = 3;
                break;
            case R.id.choosePayment_vipPay:
                PayFlag = 5;
                if (isVip == 1) {
                    if ("2".equals(aCache.getAsString("marketing_methods"))) {
                        boolean f = true;
                        if (integralPayFlag == 1) {
                            f = judgeIntegral();
                        }
                        if (!f) {
                            return;
                        }
                    }
                    if (infoBean.getLogin_type() == 2) {
                        if ("1".equals(aCache.getAsString("density_free"))) {
                            Pay();
                        } else {
                            if (infoBean.getDensity_free().equals("2")) {
                                vipPassLinear.setVisibility(View.VISIBLE);
                                vipPassPass.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        vipPassPass.requestFocus();
                                    }
                                }, 500);
                            } else if (infoBean.getDensity_free().equals("1")) {
                                Pay();
                            }
                        }
                    } else {
                        Pay();
                    }
                } else {
                    VipLoginDialog.newInstance()
                            .callback(o -> {
                                infoBean = (VipListBean.InfoBean) o;
                                Message msg = new Message();
                                msg.what = 1;
                                handler.sendMessage(msg);
                            })
                            .startShow(getSupportFragmentManager(), "")
                            .setCancelable(false);
//                    choosePaymentVipLoginLinear.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.choosePayment_vipLogin_sure:
                if ("".equals(choosePaymentVipLoginEdit.getText().toString().trim())) {
                    Toast.makeText(context, "請先輸入會員賬號", Toast.LENGTH_SHORT).show();
                    return;
                }
//                GetVipInfo();
                break;
            case R.id.choosePayment_vipLogin_close:
                choosePaymentVipLoginEdit.setText("");
                choosePaymentVipLoginLinear.setVisibility(View.GONE);
                break;
            case R.id.choosePayment_vipLogin_linear:
                break;
            case R.id.choosePayment_onlinePay_scavenging:
                startQrCode();
                break;
            case R.id.choosePayment_onlinePay_sure:
                if ("".equals(choosePaymentOnlinePayEdit.getText().toString()) ||
                        choosePaymentOnlinePayEdit.getText().toString().length() != 18) {
                    Toast.makeText(context, "請掃描正確的付款碼", Toast.LENGTH_SHORT).show();
                    return;
                }
                xPayTask();
                break;
            case R.id.choosePayment_onlinePay_close:
                choosePaymentOnlinePayLinear.setVisibility(View.GONE);
                break;
            case R.id.choosePayment_money:
                if(mViewModel.getMoneyEditValue()<mViewModel.getMoney()){
                    Toast.makeText(context, "實付金額不能少於應付金額", Toast.LENGTH_SHORT).show();
                    mViewModel.showMoneyEdit();
                    return;
                }
                if ("2".equals(aCache.getAsString("marketing_methods"))) {
                    boolean f = true;
                    if (integralPayFlag == 1) {
                        f = judgeIntegral();
                    }
                    if (!f) {
                        return;
                    }
                }
                PayFlag = 1;
                choosePaymentOtherPayName.setText(context.getResources().getString(R.string.choosePayment_money));
                choosePaymentOtherPayPayList.setVisibility(View.GONE);
                choosePaymentOtherPayPayable.setEnabled(true);
                setMoney();
                mViewModel.updateChange(true);
                choosePaymentOtherPayLinear.setVisibility(View.VISIBLE);
                break;
            case R.id.choosePayment_onlinePay_linear:
                break;
            case R.id.choosePayment_otherPay:
                if(mViewModel.getMoneyEditValue()<mViewModel.getMoney()){
                    Toast.makeText(context, "實付金額不能少於應付金額", Toast.LENGTH_SHORT).show();
                    mViewModel.showMoneyEdit();
                    return;
                }

                if ("2".equals(aCache.getAsString("marketing_methods"))) {
                    boolean f = true;
                    if (integralPayFlag == 1) {
                        f = judgeIntegral();
                    }
                    if (!f) {
                        return;
                    }
                }
                PayFlag = 7;
                choosePaymentOtherPayName.setText(context.getResources().getString(R.string.choosePayment_other));
                if (loginEntity.getData().getOtherPayList().size() > 0) {
                    otherPayList.addAll(loginEntity.getData().getOtherPayList());
                    choosePaymentOtherPayPayList.setVisibility(View.VISIBLE);
                    setOtherPayListAdapter();
                } else {
                    choosePaymentOtherPayPayList.setVisibility(View.GONE);
                }
                choosePaymentOtherPayPayable.setEnabled(false);
                mViewModel.updateChange(false);
                choosePaymentOtherPayLinear.setVisibility(View.VISIBLE);
                break;
            case R.id.choosePayment_otherPay_close:
                choosePaymentOtherPayLinear.setVisibility(View.GONE);
                break;
            case R.id.choosePayment_otherPay_sure:
                Pay(true);
                break;
            case R.id.choosePayment_otherPay_linear:
                break;
            case R.id.choosePayment_vipLogin_scavenging:
                startQrCode();
                break;
        }
    }

    // 開始掃碼
    private void startQrCode() {
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 申請權限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, Constant.REQ_PERM_CAMERA);
            return;
        }
        // 二維碼掃碼
       /*Intent intent = new Intent(context, CaptureActivity.class);
        startActivityForResult(intent, Constant.REQ_QR_CODE);*/

        Intent intent = new Intent(context, InfraredScanActivity.class);
        startActivityForResult(intent, Constant.REQ_QR_CODE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constant.REQ_PERM_CAMERA:
                // 攝像頭權限申請
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 獲得授權
                    startQrCode();
                } else {
                    // 被禁止授權
                    Toast.makeText(context, "請至權限中心打開本應用的相機訪問權限", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode != 1 && requestCode == Constant.REQ_QR_CODE && resultCode == RESULT_OK) {//掃描結果回調
            Bundle bundle = data.getExtras();
            if (3 == PayFlag) {
//                choosePaymentOnlinePayName.setText(context.getResources().getString(R.string.choosePayment_wxPay));
                choosePaymentOnlinePayLinear.setVisibility(View.VISIBLE);
                choosePaymentOnlinePayEdit.setText(bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN));

            } else if (PayFlag == 4) {
//                choosePaymentOnlinePayName.setText(context.getResources().getString(R.string.choosePayment_aliPay));
                choosePaymentOnlinePayLinear.setVisibility(View.VISIBLE);
                choosePaymentOnlinePayEdit.setText(bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN));
            } else if (PayFlag == 5) {
                choosePaymentVipLoginEdit.setText(bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN));
            } else {
                getShopCoupon(bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN));
            }
        } else if (requestCode == 100 && resultCode == 120) {
            couponIndex = data.getIntExtra("couponIndex", 9999);
            if (couponIndex != 9999) {
                tvChoosePaymentCoupon.setText(getString(R.string.satisfy) + couponList.get(couponIndex).getNeed_money() + "減" + couponList.get(couponIndex).getReduce_money());
            } else {
                tvChoosePaymentCoupon.setText(R.string.pleaseChooseCoupon1);
            }
            countMoney();
        } else if (PayFlag == 3 && requestCode == Constant.REQ_QR_CODE && resultCode == RESULT_CANCELED) {//RESULT_CANCELED =0
            String extData = MemoryCacheManager.getInstance().getScanData();
            if (extData != null && !extData.isEmpty()) {
                choosePaymentOnlinePayLinear.setVisibility(View.VISIBLE);
                choosePaymentOnlinePayEdit.setText(extData);
            }

        }
    }

    private ShopCouponInfo shopCouponInfo;

    private void getShopCoupon(String code) {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("shop_coupon_code", code);
            jsonObject.put("all_money", realPay);
            jsonObject.put("order_no", getIntent().getStringExtra("order_no"));
            jsonObject.put("vid", isVip == 1 ? infoBean.getId() : "");
            jsonObject.put("discount", 1);
            jsonObject.put("integral_cashing", integralFlag ? 1 : 0);
            jsonObject = Tools.createParameterCode(jsonObject);
            HttpUtils.post(context, Common.GET_SHOP_COUPON, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    try {
                        JSONObject json = new JSONObject(text);
                        if (json.getInt("status") == 1) {
                            shopCouponInfo = GsonUtils.JsonToBean(text, ShopCouponInfo.class);
                            Toast.makeText(context, "使用成功", Toast.LENGTH_SHORT).show();
                            ShopCouponInfo.DataBean d = shopCouponInfo.getData();
                            tvChoosePaymentShopCoupon.setText(getString(R.string.satisfy) + d.getNeed_money() + getString(R.string.couponMoney) + d.getReduce_money());
                            couponMoney = Double.parseDouble(d.getReduce_money());
                            couponIndex = 9999;
                            countMoney();
                        } else {
                            Toast.makeText(context, json.getString("message"), Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private final String MerchantID = "106832111290001";
    private void xPayTask() {
        loadingDialog.show();
        String buyerId = choosePaymentOnlinePayEdit.getText().toString().trim();
        double amount = 1.0;

        PayGateReqModel payGateReqModel = new PayGateReqModel();
        payGateReqModel.setShopID(MerchantID);
        payGateReqModel.buildPayAction();
        String detail = buildGoodsDetailTask();

        payGateReqModel.buildPayReqData(MerchantID, buyerId, realPay /*amount*/, detail);

        new PayUtils().reqPayGateTask(payGateReqModel, new PayCallback() {
            @Override
            protected void onSuccess(PayGateRespModel payRespData) {
                loadingDialog.dismiss();
                if (payRespData.paySuccess()) {
                    vipPassPass.setText("");
                    vipPassLinear.setVisibility(View.GONE);
                    mViewModel.addRemake(mOrderNo);
                    getPrintInfo(payRespData.getContent().getBillNumber(), payRespData.getContent().getLocalDate(), payRespData.getContent().getLocalTime());
                    intent = new Intent(context, PayCompleteActivity.class);
                    intent.putExtra("allPrice", MathUtil.add(allPrice, discountMoney)+"");
                    intent.putExtra("payAmount",realPay+"");
                    intent.putExtra("payType",payType);
                    intent.putExtra("otherAmount",mViewModel.getChangeEditValue());
                    intent.putExtra("isVip",isVip == 1);
                    startActivity(intent);
                    finish();
                } else {

                    Toast.makeText(context, payRespData.getMsg(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            protected void onFailure(Exception e) {
                loadingDialog.dismiss();
                Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT).show();
           /*     SimpleDateFormat dmDate = new SimpleDateFormat("yyyyMMddHHmmss");
                Date date = new Date();
                String dateran = dmDate.format(date);
                String localDate = dateran.substring(0, 8);
                String localTime = dateran.substring(8, 14);
                getPrintInfo(payGateReqModel.getData().getBillNumber(),localDate,localTime);*/
            }
        });


    }

    String buildGoodsDetailTask() {
        StringBuilder builder = new StringBuilder();
        list.forEach(goodsBean -> {
            builder.append(goodsBean.getGoods_name()).append("x").append(goodsBean.getAgoods_count());
        });
        return builder.toString();
    }

    String payType="其他收款";
    private void Pay(){
        Pay(false);
    }
    private double changeValue=0;
    /*支付*/
    private void Pay(boolean isMoney) {
        if(isMoney){
            if(mViewModel.getChangeValue()<0){
                Toast.makeText(this,"實付金額不能小於應付金額",Toast.LENGTH_SHORT).show();
                return;
            }
        }
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        changeValue=mViewModel.getChangeEditValue();
        if(isMoney){
            changeValue= mViewModel.getChangeValue();
        }
        try {
            jsonObject.put("order_no", getIntent().getStringExtra("order_no"));
            if (isVip == 1) {
                jsonObject.put("vid", infoBean.getId());
                jsonObject.put("card_code", infoBean.getPayCode());
                jsonObject.put("vip_login_type", infoBean.getLogin_type());
                jsonObject.put("density_free", infoBean.getDensity_free());
                if(changeValue==0 || isMoney){
                    jsonObject.put("changes_money","");
                }else {
                    jsonObject.put("changes_money",changeValue+"");
                }
            } else {
                if(changeValue==0 || isMoney){
                    jsonObject.put("changes_money","");
                }else {
                    jsonObject.put("changes_money",changeValue+"");
                }
            }
            if (couponIndex != 9999) {
                jsonObject.put("coupon_id", couponList.get(couponIndex).getId());
                jsonObject.put("coupon_type", couponList.get(couponIndex).getCoupon_choice_type());
            } else if (couponMoney > 0) {
                jsonObject.put("coupon_id", shopCouponInfo.getData().getId());
                jsonObject.put("coupon_type", 3);
            }
            if(isMoney){
                mMoney=mViewModel.getMoneyValue();
                jsonObject.put("amount_received",mMoney);//實收
                jsonObject.put("pay_money",realPay+"");
            }else {
                mMoney=realPay;
                jsonObject.put("amount_received",mMoney);//實收
                jsonObject.put("pay_money",realPay+"");
            }
            jsonObject.put("is_zero_storage", 0);
            jsonObject.put("discount", 1);
            jsonObject.put("all_money",realPay+"");

            if (PayFlag == 3 || PayFlag == 4) {
                jsonObject.put("code", choosePaymentOnlinePayEdit.getText().toString().trim());
            }
            //1,現金支付；3，微信支付 4,支付寶支付 5，會員支付 7,其他支付 8,賒賬
            switch (PayFlag) {
                case 1:
                    payType="現金收款";
                    jsonObject.put("pay_type", 3);//new:1.微信 2.支付寶 3.現金 5.其他支付方式 6.會員餘額
                    break;
                case 3:
                    payType="微信收款";
                    int text = Integer.parseInt(choosePaymentOnlinePayEdit.getText().toString().trim().substring(0, 2));
                    boolean aliPay = (text >= 25 && text <= 30) ? true : false;
                    boolean wxPay = (text >= 10 && text <= 15) ? true : false;
                    jsonObject.put("pay_type", aliPay ? 2 : 1);//new:1.微信 2.支付寶 3.現金 5.其他支付方式 6.會員餘額
                    break;
                case 4:
                    payType="支付寶收款";
                    jsonObject.put("pay_type", 2);//new:1.微信 2.支付寶 3.現金 5.其他支付方式 6.會員餘額
                    break;
                case 5:
                    payType="會員收款";
                    jsonObject.put("pay_type", 6);//new:1.微信 2.支付寶 3.現金 5.其他支付方式 6.會員餘額
                    break;
                case 7:
                    payType="其他收款";
                    jsonObject.put("pay_type", 5);//new:1.微信 2.支付寶 3.現金 5.其他支付方式 6.會員餘額
                    if (otherPayIndex != 9999) {
                        jsonObject.put("other_pay_id", otherPayList.get(otherPayIndex).getId());
                    }
                    break;
                case 8:
                    payType="其他收款";
                    jsonObject.put("pay_type", 7);//new:1.微信 2.支付寶 3.現金 5.其他支付方式 6.會員餘額
                    break;
            }

            jsonObject.put("password", vipPassPass.getText().toString().trim());
            jsonObject.put("combine_pay", 0);//是否開啓組合支付
            if ("1".equals(aCache.getAsString("marketing_methods"))) {
                jsonObject.put("integral_cashing", integralFlag ? 1 : 0);//是否開啓積分抵現
                jsonObject.put("integral_dis_num", needIntegral);
                jsonObject.put("integral_dis_money", needIntegralMoney);
            } else {
                if (allIntegral > 0 || needIntegral > 0 || needIntegralMoney > 0) {
                    jsonObject.put("integral_cashing", 1);//是否開啓積分抵現
                    jsonObject.put("integral_dis_num", needIntegral == 0 ? allIntegral : needIntegral);
                    jsonObject.put("integral_dis_money", needIntegralMoney);
                } else {
                    jsonObject.put("integral_cashing", 0);//是否開啓積分抵現
                }
            }

            jsonObject = Tools.createParameterCode(jsonObject);
            Log.e(TAG, "Pay: json="+jsonObject.toString());

            HttpUtils.post(context, Common.ORDER_PAY, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    try {
                        Log.e(TAG, "onSuccess: text="+text);
                        JSONObject json = new JSONObject(text);
                        Toast.makeText(context, json.getString("msg"), Toast.LENGTH_SHORT).show();
                        if (json.getInt("status") == 1) {
                            vipPassPass.setText("");
                            vipPassLinear.setVisibility(View.GONE);
                            mViewModel.addRemake(mOrderNo);
                            getPrintInfo("", "", "",mMoney,changeValue);
                            intent = new Intent(context, PayCompleteActivity.class);
                            intent.putExtra("allPrice", MathUtil.add(allPrice, discountMoney)+"");
                            intent.putExtra("payAmount",mViewModel.getMoneyValue()+"");
                            intent.putExtra("payType",payType);

                            intent.putExtra("otherAmount",changeValue+"");
                            intent.putExtra("isVip",isVip == 1);
                            startActivity(intent);
                            finish();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {
                    Log.e(TAG, "onFailure: "+e);
                    loadingDialog.dismiss();
                }
            });

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    /*獲取結算完打印信息*/
    private PrintInfoBean printInfoBean;

    private void getPrintInfo(String billNumber, String date, String time){
        getPrintInfo(billNumber,date,time,-1,-1);
    }
    /**
     * 都是退款需要的參數
     *
     * @param billNumber 交易單號 ，退款時間需要
     * @param date       訂單日期
     * @param time       訂單時間
     */
    private void getPrintInfo(String billNumber, String date, String time,double money,double changeMoeny) {
        if(!mViewModel.isPrint()){
            return;
        }
        EditText remakeView=findViewById(R.id.remark_edit);
        String value=remakeView.getEditableText().toString();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("order_no", getIntent().getStringExtra("order_no"));
            jsonObject = Tools.createParameterCode(jsonObject);
            HttpUtils.post(context, Common.GET_PRINT_INFO, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    try {
                        JSONObject json = new JSONObject(text);
                        if (json.getInt("status") == 1) {
                            printInfoBean = GsonUtils.JsonToBean(text, PrintInfoBean.class);
                            //printUtil.getInstance().print(printInfoBean);
                            try {
                                PrintInfoBean print=mViewModel.getPrintInfo(printInfoBean);
                                XprinterManager.getInstance().printPayReceipt(print);
                                DeviceServiceChannel.getInstance().printPayReceipt(print, billNumber, date, time,value,money,changeMoeny);
                            }catch (Exception e){

                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }

                @Override
                protected void onFailure(ResponseException e) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /*獲取會員信息*/
    /*private void GetVipInfo() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("vipCode", choosePaymentVipLoginEdit.getText().toString().trim());//card_num
            jsonObject = Tools.createParameterCode(jsonObject);
            HttpUtils.post(context, Common.GET_VIP_INFO, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    vipinfoBean = GsonUtils.JsonToBean(text, VipListBean.class);
                    Toast.makeText(context, vipinfoBean.getMsg(), Toast.LENGTH_SHORT).show();
                    Message msg = new Message();
                    if (vipinfoBean.getStatus() == 1) {
                        msg.what = 1;
//                        intent = new Intent(context, MemberLoginActivity.class);
//                        intent.putExtra("vipinfoBean", vipinfoBean);
//                        intent.putExtra("list", (Serializable) list);
//                        intent.putExtra("cardnum", infoBean.getPayCode());
//                        intent.putExtra("allPrice", allPrice);
//                        intent.putExtra("login_type", infoBean.getLogin_type());
//                        startActivity(intent);
//                        finish();
                    } else {
                        msg.what = 2;
                    }
                    handler.sendMessage(msg);
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }*/

}
